<?php

namespace app\api\controller\v1;

use GatewayWorker\Lib\Gateway;
use app\common\controller\BaseController;
use app\common\validate\ChatValidate;
use think\facade\Cache;
use think\Request;

class Chat extends BaseController
{
    // 初始化$registerAddress
    public function __construct()
    {
        Gateway::$registerAddress = config('gateway_worker.registerAddress');
    }
    public function get()
    {
        $userId = request()->userId;
        if(!Gateway::isUidOnline($userId)) return;
        $cache = Cache::pull('userchat_'.$userId);
        if(!$cache || !is_array($cache)) return;
        // 开始推送
        return self::showResCode('ok',$cache);
    }

    // 发送消息
    public function send(Request $request)
    {
        // 验证信息是否合法
        (new ChatValidate())->goCheck('send');
        // 组织数据
        $data = $this->resdata($request);
        $to_id = $request->to_id;
        // 验证对方是否在线
        if(Gateway::isUidOnline($to_id))
        {
            // 直接发送
            Gateway::sendToUid($to_id,json_encode($data));
            // 写入数据库
            // 返回发送成功
            return self::showResCodeWithOutData('ok');

        }
        // 不在线的话，写入消息队列

        // 获取之前的消息
        $Cache = Cache::get('userchat_'.$to_id);
        if(!$Cache || !is_array($Cache)) $Cache = [];
        $Cache[] = $data;
        // 写入数据库

        // 写入消息队列
        Cache::add('userchat_'.$to_id, $Cache);

        return self::showResCodeWithOutData('ok');

    }
    public function resdata($request)
    {
        return [
            'to_id' => $request->to_id,
            'from_id' => $request->userId,
            'from_userpic' => $request->from_userpic,
            'type' => $request->type,
            'data' => $request->data,
            'time' => time()
        ];
    }
    public function bind(Request $request)
    {
        (new ChatValidate())->goCheck('bind');
        $userId = request()->userId;
        $clientId = $request->client_id;
        // 验证数据合法性
        // 验证clinent_id合法性
        if(!Gateway::isOnline($clientId)) return TApiException('clientId不合法');
        // 验证当前客户端是否已经被绑定
        if(Gateway::getUidByClientId($clientId)) return TApiException('已被绑定');
        // 直接绑定
        Gateway::bindUid($clientId,$userId);
        // 返回结果
        return $this->showResCode('绑定成功',['type' => 'bind', 'status' => true]);

    }
}
